﻿using System;
using System.Data;
using System.IO;

namespace Algorithms.Common
{
	public static class Arguments
	{
		public static Tuple<int, double, string, string> ParseIdss(string[] args, string argNames)
		{
			TestArgCnt(args, 4, argNames);
			return Tuple.Create(
				GetInt(args[0]),
				GetDouble(args[1]),
				GetPath(args[2]),
				GetPath(args[3])
				);
		}

		private static int GetInt(string s)
		{
			int i;
			if (!int.TryParse(s, out i))
			{
				throw new ArgumentException(String.Format("Parameter is expected to be a int Second parameter {0} is expected to be a double.",
					s));
			}
			return i;
		}

		public static Tuple<double, double, string, string> ParseDdss(string[] args, string argNames)
		{
			TestArgCnt(args, 4, argNames);
			return Tuple.Create(
				GetDouble(args[0]),
				GetDouble(args[1]),
				GetPath(args[2]),
				GetPath(args[3])
				);
		}

		private static void TestArgCnt(string[] args, int i, string argNames)
		{
			if (args.Length != i)
				throw new ArgumentException("Exactly 4 arguments expected: " + argNames);
		}

		public static Tuple<double, double, string> ParseDds(string[] args)
		{
			return Tuple.Create(
				GetDouble(args[0]),
				GetDouble(args[1]),
				GetPath(args[2])
				);
		}

		private static string GetPath(string p)
		{
			if (!Path.IsPathRooted(p))
				throw new ArgumentException(string.Format("Path {0} is not a valid absolute path.", p));
			return p;
		}

		private static double GetDouble(string p)
		{
			double tau;
			if (!double.TryParse(p, out tau))
			{
				throw new ArgumentException(String.Format("Parameter is expected to be a double Second parameter {0} is expected to be a double.",
					p));
			}
			return tau;
		}

		public static Tuple<string, string> ParseSs(string[] args, string argNames)
		{
			TestArgCnt(args, 2, argNames);
			return Tuple.Create(
				args[0],
				GetPath(args[1])
				);
		}

		public static string[,] ReturnValue(DataTable tbl, string[] headers = null)
		{
			var headerCnt = tbl.Columns.Count;
			var rv = new string[tbl.Rows.Count + 1, headerCnt];
			if (headers != null)
			{
				for (var i = 0; i < headers.Length; i++)
				{
					rv[0, i] = headers[i];
				}
			}
			else
			{
				for (var i = 0; i < tbl.Columns.Count; i++)
				{
					rv[0, i] = tbl.Columns[i].ColumnName;
				}
			}

			for (var row = 0; row < tbl.Rows.Count; row++)
			{
				//first column is grouping Id.
				//last column is count
				var items = tbl.Rows[row].ItemArray;
				for (var i = 0; i < headerCnt; i++)
				{
					rv[row + 1, i] = items[i].ToString();
				}
			}
			return rv;
		}
	}
}
